Vue.component('money-format', {
  template: `
    <el-input ref="money" v-model="formatValue" :placeholder="translate(placeholder)" :class="{'error':errorType=== true}" v-bind="$props" validate-event maxlength="20" @blur="handleBlur" @focus="handleFocus">
      <template slot="append">
        <slot v-if="$slots.append" name="append" />
      </template>
    </el-input>
  `,
  model: {
    prop: 'value',
    event: 'change'
  },
  props: {
    placeholder: {
      type: String,
      default: ''
    },
    unit: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readonly: {
      type: Boolean,
      default: false
    },
    currency: {
      type: String,
      default: ''
    },
    currencyDisplay: {
      type: String,
      default: 'symbol'
    },
    size: {
      type: String,
      default: undefined
    },
    value: {
      type: [Number, String],
      default: '',
      desc: '数值'
    }
  },
  data() {
    return {
      current: '',
      formatValue: '',
      errorType: false,
      unitVal: '',
      recordList: [],
      storageLanguageJson: {}
    }
  },
  watch: {
    value(value) {
      this.calcFormatValue(value)
    }
  },
  mounted() {
    if (window.localStorage['language']) {
      var localStorage = window.localStorage['language']
      this.storageLanguageJson = JSON.parse(window.localStorage['language_' + localStorage])
    }
    this.calcFormatValue(this.value)
    // console.log(this.unit)
    // console.log(this.$props.unit)
  },
  methods: {
    translate(key) {
      if (window.localStorage['language'] && window.localStorage['language'] !== 'zh_cn') {
        setTimeout(() => {
          for (var i in this.storageLanguageJson) {
            if (i === key) {
              // console.log(this.storageLanguageJson[i])
              return this.storageLanguageJson[i]
            } else {
              return key
            }
          }
        }, 1000);
      } else {
        return key
      }
    },
    handleFocus() {
      // 获取焦点去掉千分位
      if (this.formatValue) {
        var x = this.formatValue.split(',')
        this.formatValue = parseFloat(x.join(''))
      }
    },
    handleBlur() {
      if (this.formatValue === '') {
        this.current = ''
      } else {
        let value = this.formatValue
        try {
          value = +this.formatValue.replace(/,/g, '')
        } catch {
          console.error()
        }
        if (isNaN(value)) {
          value = 0
        }
        if (this.unit === 'w') {
          value *= 10000
        }
        if (value > 999000000000000) {
          this.error()
          this.errorType = true
          value = this.recordList.slice(-1)
          setTimeout(() => {
            this.errorType = false
          }, 1000)
          if (value && value.length > 0) {
            if (this.unit === 'rate') {
              this.current = +Number(value).toFixed(4)
            } else {
              this.current = +Number(value).toFixed(2)
            }
          } else {
            this.current = ''
          }
        } else {
          this.recordList.push(value)
          if (this.unit === 'rate') {
            this.current = +Number(value).toFixed(4)
          } else {
            this.current = +Number(value).toFixed(2)
          }
        }
        this.calcFormatValue(this.current)
      }
      this.emit()
    },
    // 金额过大错误提示
    error() {
      // 多个提示标签覆盖问题.
      setTimeout(() => {
        this.$message({ showClose: true, message: '警告，金额不能大于等于千万亿！', type: 'error' })
      })
    },
    calcFormatValue(v) {
      var value = v
      if (value > 999000000000000) {
        this.errorType = true
        this.error()
        value = this.recordList.slice(-1)
        setTimeout(() => {
          this.errorType = false
        }, 1000)
      }
      if (value === '' || value === null) {
        this.current = this.formatValue = ''
      } else {
        if (this.unit === 'w') {
          value = value / 10000
        }
        this.formatValue = this.decimalFormat(value, this.unit)
      }
    },
    decimalFormat(value, unit) {
      // 强制保留4位小数
      if (unit === 'rate') {
        return value.toLocaleString('zh', { minimumFractionDigits: 4 })
      }
      if (unit === 'w') {
        return value.toLocaleString('zh', { maximumFractionDigits: 6 })
      } else {
        return value.toLocaleString('zh', { maximumFractionDigits: 2 })
      }
    },
    emit() {
      this.$emit('input', this.current)
      this.$emit('change', this.current)
    }
  }
})
